import { getToken, setToken, removeToken } from '@/utils/auth'
import { userLoginService, userGetInfoService } from '@/api/user'

const state = {
  token: getToken(),
  // 用户信息
  userInfo: {}
}

const mutations = {
  // 设置 token
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 移除 token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  // 登录
  async login(context, data) {
    const token = await userLoginService(data)
    context.commit('setToken', token)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const userInfo = await userGetInfoService()
    context.commit('setUserInfo', userInfo)
  },
  // 退出登录
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
